package com.global.emc.spring.method.support.chain;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.global.emc.core.CoreUser;
import com.global.emc.core.exception.impl.EMCException;

public class MonitorPerformanceChain extends BlankCallMethodChain{
	
	private static final String BEGIN_CURRENT_TIME = "beginCurrentTime";
	private static final String CORE_USER_UNIQUE_ID = "coreUserUniqueId";
	
	@Override
	public Map<String,Object> invoker(BeforeCallMethodContent content) throws EMCException {
		Long beginCurrentTime = System.currentTimeMillis();
		
		HttpServletRequest request = content.getRequest().getNativeRequest(HttpServletRequest.class);
		CoreUser coreUser = (CoreUser) request.getSession().getAttribute(CoreUser.CORE_USER);
		String uniqueId = (coreUser == null ? "NOUSER" : coreUser.getUniqueId());
		
		Map<String,Object> beforeCallMethodReturnValue = new HashMap<String,Object>(1);
		super.addReturnValue(beforeCallMethodReturnValue, BEGIN_CURRENT_TIME, beginCurrentTime);
		super.addReturnValue(beforeCallMethodReturnValue, CORE_USER_UNIQUE_ID, uniqueId);
		
		this.logger.info(new StringBuffer().append("trs begin")
				.append("(").append(beginCurrentTime).append(")===>")
				.append(" userId:").append(uniqueId)
				.append(" ThdId:").append(Thread.currentThread().getId())
				.append(" TrsId:").append(content.getObj().getClass().getName()).append(".").append(content.getMethod().getName())
		);
		
		return beforeCallMethodReturnValue;
	}

	@Override
	public void invoker(AfterCallMethodContent content) throws EMCException {
		Long beginCurrentTime=(Long)super.getBeforeCallMethodReturnValue(content.getBeforeCallMethodReturnValue(), BEGIN_CURRENT_TIME);
		Long endCurrentTime = System.currentTimeMillis();
		String uniqueId = (String)super.getBeforeCallMethodReturnValue(content.getBeforeCallMethodReturnValue(), CORE_USER_UNIQUE_ID);
		
		super.logger.info(new StringBuffer().append("trs end  ")
				.append("(").append(endCurrentTime).append(")===>")
				.append(" userId:").append(uniqueId)
				.append(" ThdId:").append((Thread.currentThread().getId()))
				.append(" TrsId:").append((content.getObj().getClass().getName())).append(".").append(content.getMethod().getName())
				.append(" ExTime:").append((endCurrentTime-beginCurrentTime))
		);
		
	}
	
	
}
